<script setup>
import {onBeforeUnmount, onMounted, reactive, ref} from 'vue'
import {io} from 'socket.io-client'

import MapContainer from "@/components/MapContainer.vue";

// 系统状态
const systemStatus = ref('connecting') // connecting, connected, error
const connectionError = ref('')
const lastUpdateTime = ref('')
const detectionStats = ref({
  fire: 0,
  smoke: 0,
  people: 0,
  climb: 0,
  fight: 0
})

// 视频和检测数据
const videoSrc = ref('')
const videoAspectRatio = ref(16 / 9) // 默认16:9
const videoContainer = ref(null)
const videoPlayer = ref(null)

// RTMP输入相关
const showRtmpDialog = ref(true)
const rtmpUrl = ref('')
const rtmpError = ref('')

// 位置信息
const locationData = reactive({
  latitude: 0,
  longitude: 0,
  timestamp: null,
  name: ''
})

// WebSocket连接
let socket = null

// 连接WebSocket
const connectWebSocket = () => {
  systemStatus.value = 'connecting'

  const socketUrl = import.meta.env.DEV
      ? `ws://${window.location.hostname}:5000`
      : window.location.origin

  socket = io(socketUrl, {
    reconnection: true,
    reconnectionAttempts: 5,
    reconnectionDelay: 1000,
    timeout: 20000
  })

  socket.on('connect', () => {
    systemStatus.value = 'connected'
    connectionError.value = ''
    console.log('WebSocket connected')
  })

  socket.on('disconnect', () => {
    systemStatus.value = 'error'
    connectionError.value = '与服务器的连接已断开，正在尝试重新连接...'
    console.log('WebSocket disconnected')
  })

  socket.on('connect_error', (err) => {
    systemStatus.value = 'error'
    connectionError.value = `连接错误: ${err.message}`
    console.error('WebSocket connection error:', err)
  })

  // 接收计数数据
  socket.on('detection_counts', (data) => {
    try {
      // 更新统计信息
      updateDetectionStats(data.counts)
      lastUpdateTime.value = new Date().toLocaleTimeString()
    } catch (err) {
      console.error('Error processing count data:', err)
    }
  })

  // 接收位置数据
  socket.on('location_update', (data) => {
    try {
      locationData.latitude = data.latitude
      locationData.longitude = data.longitude
      locationData.timestamp = data.timestamp
      locationData.name = data.name || '未命名位置'
    } catch (err) {
      console.error('Error processing location data:', err)
    }
  })
}

// 更新检测统计
const updateDetectionStats = (counts) => {
  // 使用传入的计数数据更新统计信息
  Object.keys(detectionStats.value).forEach(key => {
    detectionStats.value[key] = counts[key] || 0
  })
}

// 获取检测类型图标
const getDetectionIcon = (className) => {
  const icons = {
    fire: '🔥',
    smoke: '💨',
    people: '🚶',
    climb: '🧗',
    fight: '⚔️'
  }
  return icons[className] || '⚠️'
}

const getDetectionName = (className) => {
  const names = {
    fire: '火焰',
    smoke: '烟雾',
    people: '行人',
    climb: '翻越围栏',
    fight: '打斗'
  }
  return names[className] || '未知类型'
}

// 提交RTMP地址并开始视频流
const submitRtmpUrl = () => {
  if (!rtmpUrl.value.trim()) {
    rtmpError.value = '请输入有效的RTMP地址'
    return
  }

  rtmpError.value = ''
  showRtmpDialog.value = false

  // 通过后端API启动检测
  fetch('http://localhost:5000/api/start_detection', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json'
    },
    body: JSON.stringify({rtmp_url: rtmpUrl.value})
  })
      .then(response => response.json())
      .then(data => {
        if (data.status === 'success') {
          // 设置视频源为后端返回的流URL
          videoSrc.value = 'http://localhost:5000' + data.stream_url
        } else {
          connectionError.value = data.error || '启动视频流失败'
        }
      })
      .catch(err => {
        connectionError.value = `请求错误: ${err.message}`
      })
}

// 生命周期钩子
onMounted(() => {
  connectWebSocket()
})

onBeforeUnmount(() => {
  if (socket) {
    socket.disconnect()
  }
})
</script>

<template>
  <div class="app-container">
    <!-- 顶部导航栏 -->
    <header class="app-header">
      <div class="logo-container">
        <img src="@/assets/jlu_logo.svg" alt="吉林大学logo" class="logo-image">
        <h1 class="logo-text">无人机智能安防监测系统</h1>
      </div>
      <div class="status-indicator" :class="systemStatus">
        <span class="status-dot"></span>
        <span class="status-text">
          {{
            systemStatus === 'connecting' ? '连接中...' :
                systemStatus === 'connected' ? '已连接' : '连接错误'
          }}
        </span>
      </div>
    </header>

    <!-- 主内容区 -->
    <main class="app-content">
      <!-- 视频区域 -->
      <div class="video-section">
        <div class="video-container" ref="videoContainer">
          <img
              v-if="videoSrc"
              ref="videoPlayer"
              :src="videoSrc"
              class="video-frame"
              alt="实时视频流"
              @load="() => videoAspectRatio = videoPlayer.naturalWidth / videoPlayer.naturalHeight"
          />

          <!-- 无视频时的占位 -->
          <div v-if="!videoSrc" class="video-placeholder">
            <div class="placeholder-icon">📹</div>
            <p>等待视频流连接...</p>
          </div>
        </div>
      </div>

      <!-- 侧边信息栏 -->
      <div class="sidebar">
        <div class="sidebar-content">
          <!--
          <div class="info-card status-card">
            <div class="card-content">
              <h3 class="card-title">系统状态</h3>
              <div class="status-grid">
                <div class="status-item">
                  <span class="status-label">连接状态:</span>
                  <span class="status-value" :class="systemStatus">
                    {{
                      systemStatus === 'connecting' ? '连接中' :
                          systemStatus === 'connected' ? '正常' : '异常'
                    }}
                  </span>
                </div>
                <div class="status-item">
                  <span class="status-label">最后更新:</span>
                  <span class="status-value">{{ lastUpdateTime || '无数据' }}</span>
                </div>
              </div>

              <div v-if="connectionError" class="error-message">
                {{ connectionError }}
              </div>
            </div>
          </div>
          -->

          <!-- 检测统计卡片 -->
          <div class="info-card stats-card">
            <div class="card-content">
              <h3 class="card-title">检测统计</h3>
              <div class="stats-grid">
                <div
                    v-for="(count, className) in detectionStats"
                    :key="className"
                    class="stat-item"
                >
                  <span class="stat-icon">{{ getDetectionIcon(className) }}</span>
                  <span class="stat-label">{{ getDetectionName(className) }}:</span>
                  <span class="stat-value">{{ count }}</span>
                </div>
              </div>
            </div>
          </div>

          <!-- 位置信息卡片 -->
          <div class="info-card location-card">
            <div class="card-content">
              <h3 class="card-title">实时位置</h3>
              <MapContainer/>

              <div class="location-info" v-if="locationData.timestamp">
                <div class="location-item">
                  <span class="location-label">位置名称:</span>
                  <span class="location-value">{{ locationData.name }}</span>
                </div>
                <!--
                <div class="location-timestamp">
                  更新时间: {{ formatTimestamp(locationData.timestamp) }}
                </div>
                -->
              </div>

              <div v-else class="empty-location">
                暂无位置数据
              </div>
            </div>
          </div>
        </div>

      </div>
    </main>

    <!-- RTMP地址输入对话框 -->
    <div v-if="showRtmpDialog" class="rtmp-dialog-overlay">
      <div class="rtmp-dialog">
        <h3 class="dialog-title">输入RTMP视频流地址</h3>
        <div class="dialog-content">
          <div class="input-group">
            <label for="rtmp-input">RTMP地址:</label>
            <input
                id="rtmp-input"
                v-model="rtmpUrl"
                type="text"
                placeholder="例如: rtmp://example.com/live/stream"
                @keyup.enter="submitRtmpUrl"
            >
            <div v-if="rtmpError" class="input-error">{{ rtmpError }}</div>
          </div>
          <div class="dialog-actions">
            <button class="submit-btn" @click="submitRtmpUrl">确认</button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped>
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

body {
  background-color: #121212;
  color: rgba(255, 255, 255, 0.87);
  font-family: 'Segoe UI', 'Roboto', 'Oxygen', 'Ubuntu', sans-serif;
  line-height: 1.6;
}

.app-container {
  display: flex;
  flex-direction: column;
  min-height: 100vh;
  background-color: #121212;
}

/* 头部样式 */
.app-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 1rem 2rem;
  background-color: #1e1e1e;
  box-shadow: 0 4px 6px rgba(0, 0, 0, 0.3);
  z-index: 10;
}

.logo-container {
  display: flex;
  align-items: center;
  gap: 1rem;
}

.logo-image {
  height: 50px;
  width: auto;
  background-color: #fff;
  border-radius: 50%;
}

.logo-text {
  font-size: 1.5rem;
  font-weight: 600;
  background: linear-gradient(to right, #768fff, #00c853);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
}

.status-indicator {
  display: flex;
  align-items: center;
  gap: 0.5rem;
  padding: 0.5rem 1rem;
  border-radius: 20px;
  background-color: #2d2d2d;
  transition: all 0.3s ease;
}

.status-dot {
  width: 10px;
  height: 10px;
  border-radius: 50%;
  background-color: rgba(255, 255, 255, 0.6);
}

.status-indicator.connected .status-dot {
  background-color: #00c853;
  box-shadow: 0 0 8px #00c853;
}

.status-indicator.error .status-dot {
  background-color: #ff1744;
  box-shadow: 0 0 8px #ff1744;
}

.status-indicator.connecting .status-dot {
  background-color: #ff9100;
  animation: pulse 1.5s infinite;
}

@keyframes pulse {
  0% {
    opacity: 0.5;
  }
  50% {
    opacity: 1;
  }
  100% {
    opacity: 0.5;
  }
}

/* 主内容区样式 */
.app-content {
  display: flex;
  flex: 1;
  padding: 1.5rem;
  gap: 1.5rem;
  overflow: hidden;
}

.video-section {
  flex: 3;
  display: flex;
  flex-direction: column;
  min-width: 0;
}

.video-container {
  position: relative;
  flex: 1;
  background-color: #000;
  border-radius: 8px;
  overflow: hidden;
  display: flex;
  align-items: center;
  justify-content: center;
  aspect-ratio: v-bind(videoAspectRatio);
  max-height: calc(100vh - 180px);
}

.video-frame {
  max-width: 100%;
  max-height: 100%;
  object-fit: contain;
}

.video-placeholder {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  color: rgba(255, 255, 255, 0.6);
  gap: 1rem;
}

.placeholder-icon {
  font-size: 3rem;
  opacity: 0.5;
}

/* 侧边栏样式 */
.sidebar {
  flex: 1;
  min-width: 300px;
  display: flex;
  flex-direction: column;
  gap: 1.5rem;
  max-height: calc(100vh - 180px);
  overflow-y: auto;
}

.sidebar-content {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 1.5rem;
}

.info-card {
  background-color: #1e1e1e;
  border-radius: 8px;
  padding: 1.5rem;
  box-shadow: 0 4px 6px rgba(0, 0, 0, 0.3);
  flex: 1;
  display: flex;
  flex-direction: column;
}

.info-card:first-child {
  flex: 0 0 auto;
}

.info-card:not(:first-child) {
  flex: 1;
  min-height: 0;
}

.card-content {
  flex: 1;
}

.card-content.location {
  gap: 1.5rem;
}

.card-title {
  margin-bottom: 1rem;
  font-size: 1.1rem;
  color: #768fff;
  display: flex;
  align-items: center;
  gap: 0.5rem;
}

.status-grid {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 1rem;
}

.status-item {
  display: flex;
  flex-direction: column;
}

.status-label {
  font-size: 0.85rem;
  color: rgba(255, 255, 255, 0.6);
}

.status-text {
  color: rgba(255, 255, 255, 0.87);
}

.status-value {
  font-weight: 500;
  margin-top: 0.25rem;
  color: rgba(255, 255, 255, 0.87);
}

.status-value.connected {
  color: #00c853;
}

.status-value.error {
  color: #ff1744;
}

.error-message {
  margin-top: 1rem;
  padding: 0.75rem;
  background-color: rgba(255, 23, 68, 0.1);
  border-left: 3px solid #ff1744;
  border-radius: 0 4px 4px 0;
  font-size: 0.85rem;
  color: rgba(255, 255, 255, 0.6)
}

.stats-grid {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 1rem;
}

.stat-item {
  display: flex;
  align-items: center;
  gap: 0.5rem;
  padding: 0.5rem;
  background-color: #2d2d2d;
  border-radius: 4px;
}

.stat-icon {
  font-size: 1.2rem;
}

.stat-label {
  flex: 1;
  font-size: 0.9rem;
  text-transform: capitalize;
  color: rgba(255, 255, 255, 0.87);
}

.stat-value {
  font-weight: bold;
  color: #ffffff;
}

/* 位置信息卡片样式 */
.location-info {
  background-color: #2d2d2d;
  border-radius: 8px;
  padding: 1rem;
  border: 1px solid rgba(255, 255, 255, 0.1);
}

.location-item {
  margin-bottom: 0.75rem;
}

.location-label {
  font-size: 0.85rem;
  color: rgba(255, 255, 255, 0.6);
  display: block;
  margin-bottom: 0.25rem;
}

.location-value {
  font-weight: 500;
  color: #ffffff;
}

.location-coordinates {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 0.75rem;
  margin-bottom: 0.75rem;
}

.coordinate-item {
  background-color: rgba(255, 255, 255, 0.05);
  padding: 0.5rem;
  border-radius: 4px;
}

.coordinate-label {
  font-size: 0.75rem;
  color: rgba(255, 255, 255, 0.6);
  display: block;
}

.coordinate-value {
  font-family: 'Roboto Mono', monospace;
  font-weight: 500;
  color: rgba(255, 255, 255, 0.87);
}

.location-timestamp {
  font-size: 0.8rem;
  color: rgba(255, 255, 255, 0.5);
  text-align: right;
  margin-top: 0.5rem;
}

.empty-location {
  padding: 1.5rem;
  text-align: center;
  color: rgba(255, 255, 255, 0.6);
  background-color: #2d2d2d;
  border-radius: 8px;
  border: 1px solid rgba(255, 255, 255, 0.1);
}

/* RTMP对话框样式 */
.rtmp-dialog-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.8);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 100;
}

.rtmp-dialog {
  background-color: #1e1e1e;
  border-radius: 12px;
  width: 90%;
  max-width: 500px;
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.5);
  overflow: hidden;
}

.dialog-title {
  padding: 1.5rem;
  font-size: 1.2rem;
  color: #ffffff;
  background-color: #2d2d2d;
  border-bottom: 1px solid rgba(255, 255, 255, 0.1);
}

.dialog-content {
  padding: 1.5rem;
}

.input-group {
  margin-bottom: 1.5rem;
}

.input-group label {
  display: block;
  margin-bottom: 0.5rem;
  color: rgba(255, 255, 255, 0.87);
}

.input-group input {
  width: 100%;
  padding: 0.75rem 1rem;
  background-color: #2d2d2d;
  border: 1px solid rgba(255, 255, 255, 0.1);
  border-radius: 6px;
  color: #ffffff;
  font-size: 1rem;
  transition: all 0.3s ease;
}

.input-group input:focus {
  border-color: #2962ff;
  outline: none;
  box-shadow: 0 0 0 2px rgba(41, 98, 255, 0.3);
}

.input-error {
  color: #ff1744;
  font-size: 0.85rem;
  margin-top: 0.5rem;
}

.dialog-actions {
  display: flex;
  justify-content: flex-end;
}

.submit-btn {
  padding: 0.75rem 2rem;
  background-color: #2962ff;
  color: #ffffff;
  border: none;
  border-radius: 6px;
  font-size: 1rem;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.3s ease;
}

.submit-btn:hover {
  background-color: #0039cb;
}

/* 响应式样式 */
@media (max-width: 1200px) {
  .app-content {
    flex-direction: column;
  }

  .sidebar {
    min-width: 100%;
    max-height: none;
  }

  .video-container {
    max-height: none;
  }
}

@media (max-width: 768px) {
  .app-header {
    padding: 1rem;
  }

  .logo-text {
    font-size: 1.2rem;
  }

  .status-grid,
  .stats-grid {
    grid-template-columns: 1fr;
  }

  .location-coordinates {
    grid-template-columns: 1fr;
  }
}

/* 滚动条样式 */
::-webkit-scrollbar {
  width: 6px;
  height: 6px;
}

::-webkit-scrollbar-track {
  background: #2d2d2d;
  border-radius: 3px;
}

::-webkit-scrollbar-thumb {
  background: #2962ff;
  border-radius: 3px;
}

::-webkit-scrollbar-thumb:hover {
  background: #768fff;
}
</style>